<?php

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // 调用方法
    $method = $_POST['method'];
    if (function_exists($method)) {
        call_user_func($method);
    }
}
function setSession(){
    $context = json_decode($_POST['context'] ?: "[]") ?: [];
    $postData = [
        "model" => "gpt-3.5-turbo-0301",
        "temperature" => 0,
        "stream" => true,
        "messages" => [],
    ];
    if (!empty($context)) {
        $context = array_slice($context, -5);
        foreach ($context as $message) {
            $postData['messages'][] = ['role' => 'user', 'content' => str_replace("\n", "\\n", $message[0])];
            $postData['messages'][] = ['role' => 'assistant', 'content' => str_replace("\n", "\\n", $message[1])];
        }
    }

    $postData['messages'][] = ['role' => 'user', 'content' => $_POST['message']];
    $postData = json_encode($postData);
    session_start();


    $_SESSION['data'] = $postData;
    if ((isset($_POST['key'])) && (!empty($_POST['key']))) {
        $_SESSION['key'] = $_POST['key'];
    }
    include_once "Verify.php";
    $verify = Verify::instance($_POST['key']);
    if (empty($_SESSION['system_app_key'])){
        $verify->changeKey();
    }
    $verify->log($_POST['message']);
    print_r($verify->key());die;
}

//function setSession(){
//
//    session_start();
//
//    if ((isset($_POST['key'])) && (!empty($_POST['key']))) {
//        $_SESSION['key'] = $_POST['key'];
//    }
//    include_once "Verify.php";
//    $verify = Verify::instance($_POST['key']);
//    if (empty($_SESSION['system_app_key'])){
//        $verify->changeKey();
//    }
//    $verify->log($_POST['message']);
//    print_r(json_encode(['key'=>json_decode($verify->key()),'resp'=>getAnswer($_POST['message'])]));die;
//}



function getAnswer($text){
    $OPENAI_API_KEY = $_SESSION['system_app_key'];



    $headers  = [
        'Accept: application/json',
        'Content-Type: application/json',
        'Authorization: Bearer '.$OPENAI_API_KEY
    ];
    $url = "https://openai.1rmb.tk/v1/completions";
//    $url = "https://api.openai.com/v1/chat/completions";

//    $params = [
//        'model' => "gpt-3.5-turbo",
//        'messages' => [
//            [
//                'role' => 'user',
//                'content'=> $text
//            ]
//        ],
//        'max_tokens' => 512
//    ];
    $params = [
        'model' => "text-davinci-003",
        'prompt' => $text,
        "max_tokens"=> 1024,
        "temperature"=> 0.7
    ];

    $res = chatGptCurl($url,$params,$headers);
    if (!isset($res['error']['code'])){
        return ['msg'=>$res['choices'][0]['text'],'code'=>true];
//        return ['msg'=>$res['choices'][0]['message']['content'],'code'=>true];
    }else{
        return ['msg'=>$res['error']['code'],'code'=>false];
    }

}

function chatGptCurl($url,$params,$headers)
{
    set_time_limit(0);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params,JSON_UNESCAPED_UNICODE));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    $response_data = json_decode($response, true);
    if (curl_errno($ch)) {

        echo 'Error: ' . curl_error($ch);

    }
    curl_close($ch);

    return $response_data;

}



// 更换密钥
function changeKey(){
    include_once "Verify.php";
    $verify = Verify::instance('');
    print_r($verify->changeKey());die;
}

//查看剩余次数
function getCount(){
    include_once "Verify.php";
    $verify = Verify::instance($_POST['key']);
    print_r($verify->getCount());die;
}

function dec(){
    include_once "Verify.php";
    Verify::instance($_POST['key'])->dec();
}

